<template>
  <div class="app-container">
    <el-form label-width="120px" :model="scores" :rules="formRules" ref="dataForm">
      <el-form-item label="成绩" prop="score">
        <el-input-number v-model.number="scores.score" placeholder="请输入成绩" :type="'number'" :step="1" :precision="2" :min="0" :max="100"></el-input-number>
      </el-form-item>
      <el-form-item label="班级">
          <el-cascader
              v-model="classId"
              :options="classOptions"
              :props="{ expandTrigger: 'hover' }"
              @change="handleChange"></el-cascader>
      </el-form-item>
      <el-form-item label="考试日期" prop="examId">
        <el-select v-model="scores.examId" filterable clearable placeholder="请选择考试信息">
            <el-option
                v-for="option in examOptions"
                :key="option.id"
                :label="`${option.examDate} ${option.comment ? '- ' + option.comment : ''}`"
                :value="option.id">
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="学生" v-show="classId" prop="studentId">
          <!-- 可搜索下拉框 -->
          <el-select
              v-model="scores.studentId"
              :multiple="false"
              filterable
              :clearable="true"
              remote
              reserve-keyword
              placeholder="请输入学生"
              :remote-method="remoteMethod"
              :loading="findStudentLoading">
              <el-option
                v-for="item in studentOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import students from '@/api/cms/students'
import classes from '@/api/cms/classes' 
import exams from '@/api/cms/exams'
import examScores from '@/api/cms/examScores'  
export default {
  data() {
    return {
      // 存放学生信息
      scores: {
        examId: '',
        studentId: '',
        score: 0.00
      },
      saveBtnDisabled: false, // 保存按钮是否禁用
      classId: undefined,
      formRules: {
          score: [
              { required: true, message: '请输入成绩', trigger: 'blur' }
          ],
          studentId: [
              { required: true, message: '请输入学生', trigger: 'blur' }
          ],
          examId: [
              { required: true, message: '请输入考试信息', trigger: 'blur' }
          ]
          
      },
      classOptions: undefined,
      studentOptions: undefined,
      examOptions: undefined,
      findStudentLoading: false,
    }
  },
  watch: {
    $route(to, from) { // 监听路由变化方式
      this.init()
    },
    classId(newValue, oldValue) {
      // 在 classId 值变化时执行的操作
      console.log('classId 值已更改：', newValue);
      this.getStudentsName();
    }
  },
  created() {
    // 初始化方法
    this.init();
  },
  methods: {
    // 搜索
    remoteMethod(query) {
      console.log(query)
      if (query !== '') {
        this.findStudentLoading = true;
        this.getStudentsName(query);
      }else {
        this.studentOptions = []
      }
    },
    getStudentsName(query = '') {
      let params = {
          classId:this.classId,
          name:query
        }
        students.getStudentsName(params).then(res=>{
          console.log(res)
          this.studentOptions = res.data.items
        }).catch(err=>{
          console.log(err)
        }).finally(()=>{
          this.findStudentLoading = false;
        });
    },
    init() {
      // 判断是否有id
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.getInfo(id)
      } else {
          // 做添加 清空表单
          this.scores =  {
            examId: '',
            studentId: '',
            score: 0.00
          }
      }
      // 班级信息数据
      classes.getCascaderClass().then(res=>{
          console.log(res)
          this.classOptions = res.data.content
      }).catch(err=>{
          console.log(err)
      })
      // 获取考试信息数据
      exams.findAllExams().then(res=>{
        console.log(res)
        this.examOptions = res.data.content
      }).catch(err=>{
        console.log(err)
      })
    },
    // 根据id查询方法
    getInfo(id) {
      console.log("********")
      this.classId = this.$route.query.classId;
      examScores.getInfoById(id)
        .then(response => {
          console.log(response);
          this.scores = response.data.item
        })
    },
    saveOrUpdate() {
      this.$refs.dataForm.validate(valid => {
          // console.log(valid)
          if (valid) {
          // 表单验证通过，执行提交操作
          this.saveBtnDisabled = true
          // 判断saveBtnDisabled是否有id 修改或添加
              if (!this.scores.id) {
              // 添加
              this.saveData()
              } else {
              this.updateData()
              }
          } else {
          // 表单验证失败，输出错误信息
          // console.log('不通过')
              this.$message.error('请正确输入表单');
          }
      })
    },
    // 修改教师方法
    updateData() {
      examScores.updateInfo(this.scores)
        .then(response => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.$router.push({ path: '/examsScores/table' })
        }).catch(response => {
          this.$message({
            type: 'error',
            message: '修改失败'
          })
        })
    },
    // 保存
    saveData() {
      examScores.addInfo(this.scores)
        .then(response => { // 添加成功
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          // 路由跳转
          this.$router.push({ path: '/examsScores/table' })
        }).catch(response => {
          this.$message({
            type: 'error',
            message: '保存失败'
          })
        })
    },
    handleChange(value) {      
      this.classId = value[1];
      console.log(this.classId);
    }
  }
}
</script>
